﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;

using log4net;
using DataDesign.MPP.Utilities;

using PSLibrary = Microsoft.Office.Project.Server.Library;

namespace DataDesign.MPP.ServerManager
{
    public class HelperServerManager
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region GetWebService
        public static WebSvcProject.Project GetWebSvcProject()
        {
            logger.Debug("BEGIN GetWebSvcProject");
            var ws = new WebSvcProject.Project();
            ws.UseDefaultCredentials = true;
            ws.Url = Common.GetWebServicesBaseUrl(ws.Url);
            ws.Timeout = int.Parse(Common.AppSettingKey(Constant.WS_TIME_OUT));
            logger.Debug("END GetWebSvcProject");

            return ws;
        }

        public static WebSvcResource.Resource GetWebSvcResource()
        {
            logger.Debug("BEGIN GetWebSvcResource");
            var ws = new WebSvcResource.Resource();
            ws.UseDefaultCredentials = true;
            ws.Url = Common.GetWebServicesBaseUrl(ws.Url);
            ws.Timeout = int.Parse(Common.AppSettingKey(Constant.WS_TIME_OUT));
            logger.Debug("END GetWebSvcResource");

            return ws;
        }

        public static WebSvcCustomFields.CustomFields GetWebSvcCustomFields()
        {
            logger.Debug("BEGIN GetWebSvcCustomFields");
            var ws = new WebSvcCustomFields.CustomFields();
            ws.UseDefaultCredentials = true;
            ws.Url = Common.GetWebServicesBaseUrl(ws.Url);
            ws.Timeout = int.Parse(Common.AppSettingKey(Constant.WS_TIME_OUT));
            logger.Debug("END GetWebSvcCustomFields");

            return ws;
        }

        public static WebSvcLookupTable.LookupTable GetWebSvcLookupTable()
        {
            logger.Debug("BEGIN GetWebSvcLookupTable");
            var ws = new WebSvcLookupTable.LookupTable();
            ws.UseDefaultCredentials = true;
            ws.Url = Common.GetWebServicesBaseUrl(ws.Url);
            ws.Timeout = int.Parse(Common.AppSettingKey(Constant.WS_TIME_OUT));
            logger.Debug("END GetWebSvcLookupTable");

            return ws;
        }

        #endregion

        public static void LogSoapException(string title, Exception ex, log4net.ILog logger)
        {
            if (ex is System.Web.Services.Protocols.SoapException)
            {
                PSLibrary.PSClientError error = new PSLibrary.PSClientError((System.Web.Services.Protocols.SoapException)ex);
                PSLibrary.PSErrorInfo[] errors = error.GetAllErrors();
                string errMess = "==============================\r\nError: \r\n";
                for (int i = 0; i < errors.Length; i++)
                {
                    errMess += "\n" + ex.Message.ToString() + "\r\n";
                    errMess += "".PadRight(30, '=') + "\r\nPSCLientError Output:\r\n \r\n";
                    errMess += errors[i].ErrId.ToString() + "\n";

                    for (int j = 0; j < errors[i].ErrorAttributes.Length; j++)
                    {
                        errMess += "\r\n\t" + errors[i].ErrorAttributeNames()[j] + ": " + errors[i].ErrorAttributes[j];
                    }
                    errMess += "\r\n".PadRight(30, '=');
                }
                logger.Error(title + "\r\n" + errMess);
            }
        }

        public static void AddAllFieldsToFilder(PSLibrary.Filter filter, System.Data.DataColumnCollection columnCollection)
        {
            foreach (System.Data.DataColumn column in columnCollection)
            {
                filter.Fields.Add(new PSLibrary.Filter.Field(column.ColumnName));
            }
        }

        public static string GetValueByDictionaryAndXPathDataSet(Dictionary<Guid, string> dic, XPathDataSet xpathDS, string xpath)
        {
            try
            {
                if (dic != null)
                {
                    string guid = xpathDS.SelectSingleNodeValue(xpath);
                    if (guid != null)
                        return dic[new Guid(guid)];
                }
                return null;
            }
            catch (Exception ex)
            {
                logger.Warn("ERROR GetValueByDictionaryAndXPathDataSet", ex);
                return null;
            }
        }

        public static void Load() { }

        #region CustomField Guid

        public static readonly Guid GUID_TASK_PRIORITY_LEVEL = ResourceManager.GetCustomFieldByName(ResourceUtil.GetString("NAME_TASK_PRIORITY_LEVEL"), ResourceManager.EntityType.TaskEntity).MD_PROP_UID;
        public static readonly string XPATH_PROJDS_CODE_VALUE_BY_TASK_PRIORITY_LEVEL = string.Format(XPATH_PROJDS_CODE_VALUE_BY_TASK_CUSTOM_FIELD_UID, "{0}", GUID_TASK_PRIORITY_LEVEL.ToString());

        public static readonly Guid GUID_PROJECT_CUSTOMER = ResourceManager.GetCustomFieldByName(ResourceUtil.GetString("NAME_PROJECT_CUSTOMER"), ResourceManager.EntityType.ProjectEntity).MD_PROP_UID;
        public static readonly string XPATH_PROJDS_TEXT_VALUE_BY_PROJECT_CUSTOMER = string.Format(XPATH_PROJDS_TEXT_VALUE_BY_PROJECT_MD_PROP_UID, GUID_PROJECT_CUSTOMER.ToString());

        public static readonly Guid GUID_PROJECT_COST_ESTIMATE = ResourceManager.GetCustomFieldByName(ResourceUtil.GetString("NAME_PROJECT_COST_ESTIMATE"), ResourceManager.EntityType.ProjectEntity).MD_PROP_UID;
        public static readonly string XPATH_PROJDS_TEXT_VALUE_BY_PROJECT_COST_ESTIMATE = string.Format(XPATH_PROJDS_NUM_VALUE_BY_PROJECT_MD_PROP_UID, GUID_PROJECT_COST_ESTIMATE.ToString());

        public static readonly Guid GUID_PROJECT_COST_REAL = ResourceManager.GetCustomFieldByName(ResourceUtil.GetString("NAME_PROJECT_COST_REAL"), ResourceManager.EntityType.ProjectEntity).MD_PROP_UID;
        public static readonly string XPATH_PROJDS_TEXT_VALUE_BY_PROJECT_COST_REAL = string.Format(XPATH_PROJDS_NUM_VALUE_BY_PROJECT_MD_PROP_UID, GUID_PROJECT_COST_REAL.ToString());

        public static readonly Guid GUID_PROJECT_PRIORITY_LEVEL = ResourceManager.GetCustomFieldByName(ResourceUtil.GetString("NAME_PROJECT_PRIORITY_LEVEL"), ResourceManager.EntityType.ProjectEntity).MD_PROP_UID;
        public static readonly string XPATH_PROJDS_CODE_VALUE_BY_PROJECT_PRIORITY_LEVEL = string.Format(XPATH_PROJDS_CODE_VALUE_BY_PROJECT_MD_PROP_UID, GUID_PROJECT_PRIORITY_LEVEL.ToString());
        #endregion

        #region XPath
        public const string XPATH_PROJDS_CODE_VALUE_BY_TASK_CUSTOM_FIELD_UID = "mpp:ProjectDataSet/mpp:TaskCustomFields[mpp:TASK_UID='{0}' and mpp:MD_PROP_UID='{1}']/mpp:CODE_VALUE";
        public const string XPATH_PROJDS_CODE_VALUE_BY_PROJECT_MD_PROP_UID = "mpp:ProjectDataSet/mpp:ProjectCustomFields[mpp:MD_PROP_UID='{0}']/mpp:CODE_VALUE";
        public const string XPATH_PROJDS_TEXT_VALUE_BY_PROJECT_MD_PROP_UID = "mpp:ProjectDataSet/mpp:ProjectCustomFields[mpp:MD_PROP_UID='{0}']/mpp:TEXT_VALUE";
        public const string XPATH_PROJDS_NUM_VALUE_BY_PROJECT_MD_PROP_UID = "mpp:ProjectDataSet/mpp:ProjectCustomFields[mpp:MD_PROP_UID='{0}']/mpp:NUM_VALUE";
        
        #endregion

        #region Lookup Dictionary
        public static readonly Dictionary<Guid, string> DicProjectPriorityLevel = ResourceManager.GetLookupTableDictionaryForProjectPriorityLevel();
        #endregion
    }

}
